package org.galaxyworld.flycode.utils;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.*;

public class FileWriterUtils {

    /**
     * Creates directories by Java package.
     *
     * @param outputDir the directory to create in
     * @param packageName Java package full name
     * @param includeImpl includes implementation package or not
     */
    public static void createPackageDirs(String outputDir, String packageName, boolean includeImpl) {
        String dirs = StringUtils.replace(packageName, ".", "/");
        try {
            String dirPath = FilenameUtils.normalize(outputDir + "/" + dirs);
            FileUtils.forceMkdir(new File(dirPath));
            if (includeImpl) {
                String implPath = FilenameUtils.normalize(dirPath + "/impl");
                FileUtils.forceMkdir(new File(implPath));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * Creates a Writer to the class file.
     *
     * @param outputDir file to be created in
     * @param packageName package name
     * @param fileName Java file name without ".java"
     * @return the Writer
     */
    public static Writer createWriter(String outputDir, String packageName, String fileName) {
        String targetPath = FilenameUtils.normalize(StringUtils.replace(packageName, ".", "/"));
        File targetDir = new File(outputDir, targetPath);
        if (!targetDir.exists()) {
            targetDir.mkdirs();
        }
        String path = String.format("%s/%s/%s.java", outputDir, targetPath, fileName);
        try {
            return new BufferedWriter(new FileWriter(path));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
